# Create your views here.
from django.core import serializers
from django.http import Http404, HttpResponse
from django.utils.simplejson.decoder import JSONDecoder
from mytaxisharing import models

def method_splitter(request, *args, **kwargs):
    get_view = kwargs.pop('GET', None)
    post_view = kwargs.pop('POST', None)
    put_view = kwargs.pop('PUT', None)
    delete_view = kwargs.pop('DELETE', None)
    if request.method == 'GET' and get_view is not None:
        return get_view(request, *args, **kwargs)
    elif request.method == 'POST' and post_view is not None:
        return post_view(request, *args, **kwargs)
    elif request.method == 'PUT' and put_view is not None:
        return put_view(request, *args, **kwargs)
    elif request.method == 'DELETE' and delete_view is not None:
        return delete_view(request, *args, **kwargs)
    raise Http404


def some_page_get(request, *args, **kwargs):
    risorsa = get_risorsa(**kwargs)
    if risorsa is not None:
        json_data = serializers.serialize('json', risorsa.objects.filter(**dict(request.GET.items())))
        return HttpResponse(json_data)
    raise Http404


def some_page_post(request, *args, **kwargs):
    risorsa = get_risorsa(**kwargs)
    if risorsa is not None:
        r = risorsa(**dict(request.POST.items()))
        r.save()
        json_data = serializers.serialize('json', [r])
        return HttpResponse(json_data)
    raise Http404


def some_page_put(request, *args, **kwargs):
    risorsa = get_risorsa(**kwargs)
    if risorsa is not None:
        put_data = JSONDecoder().decode(request.raw_post_data)
        id_risorsa = kwargs.pop('id', None)
        if id_risorsa is not None:
            risorsa.objects.filter(id=id_risorsa).update(**put_data)
            return HttpResponse()
    raise Http404


def some_page_delete(request, *args, **kwargs):
    risorsa = get_risorsa(**kwargs)
    if risorsa is not None:
        id_risorsa = kwargs.pop('id', None)
        if id_risorsa is not None:
            risorsa.objects.filter(id=id_risorsa).delete()
            return HttpResponse()
    raise Http404

def get_risorsa(**kwargs):
    nome_risorsa = kwargs.pop('risorsa', None)
    if nome_risorsa is None:
        return None
    try:
        return getattr(models, nome_risorsa)
    except AttributeError:
        return None
